// Copyright 2010 Shantanu Shah<shantanus@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.shansense.airplanemodetimer;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.shansense.coretimer.ChangeModeUtil;

/**
 * Listen to airplane mode changed intents. If phone just entered the airplane
 * mode, launch activity by sending an intent.
 * 
 * @author Shantanu Shah <shantanus@gmail.com>
 */
public class AirplaneModeBroadcastReceiver extends BroadcastReceiver {
  
  @Override
  public void onReceive(Context context, Intent intent) {
    if (!AirplaneModeUtil.isModeSet(context)) return;
      
    SharedPreferences settings = context.getSharedPreferences(AirplaneModeUtil.getAppName(),
        Context.MODE_PRIVATE);
    final long disabledTimeMillis = settings.getLong(ChangeModeUtil.DISABLED_TIME_MS, 0);
    if (disabledTimeMillis + ChangeModeUtil.BROADCAST_RECEIVER_DISABLED_TIME > 
        System.currentTimeMillis()) {
      return;
    }
    
    Intent newActivityIntent = new Intent();
    newActivityIntent.setAction(Intent.ACTION_MAIN);
    newActivityIntent.setClassName(context, AirplaneModeUtil.packageName + ".AirplaneModeTimer");
    newActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    newActivityIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    context.startActivity(newActivityIntent);
  }
  
  public static ComponentName componentName() {
    return new ComponentName(AirplaneModeUtil.packageName,
        AirplaneModeUtil.packageName + ".AirplaneModeBroadcastReceiver");
  }
}
